CDATA Sections

There may be times when you want to store information that you do not want an XML processor to look at.  You may want to store some information that an XML processor would have a tough time dealing with, and you want your applications to have access to it without it being translated.  Considering how picky XML processors are, how can we accomplish this?  Easily.  This type of data should be stored in CDATA sections.  

CDATA stands for character data.  XML processors ignore everything in a CDATA section.  The syntax is:

<![CDATA[data you want left alone]]>

Nothing between the opening tag (<![CDATA[) and the closing tag (]]>) will be recognized by the processor as markup.  

Warnings:	Do not make the mistake of having an end tag (]]>) as part of your data!  This will result in a non-synchronous logical structure, which in turn will cause fatal errors.

Also, do not add spaces or tags to the beginning or end tags as it too will result in fatal errors.

A common mistake among those new to XML is to use comments to embed data.  Do not use comments for this purpose!  By its specification, comments are not required to be passed from the XML document to an application by an XML processor.  In other words, your application is not guaranteed access to comments.  It is however guaranteed access to CDATA sections.  

The following code is an updated version of our original employee XML document.  It includes a section of free form text as an employee review area.

<?xml version="1.0"?>
<employees>
    <employee id="A1234">
        <name>
            <first>John</first>
            <last>Doe</last>
        </name>
        <position>Programmer</position>
        <address>
            <street>123 Main Street</street>
            <city>Anywhere</city>
            <state>CA</state>
            <zip>92000</zip>
        </address>
        <phone>
            <main>(714) 555-1000</main>
            <fax>(714) 555-1001</fax>
        </phone>
	<![CDATA[John is a technical lead on several projects and has always worked well with his co-workers.]]>
    </employee>
</employees>

File: Chapter 3\CDATA.xml

One of the ways that CDATA is used is to embed binary information that has been UUENCODED (converted to a character equivalent).  A good example of this is the embedding of UUENCODED image files within an XML document.  While there is nothing prohibiting this, there are better ways to reference binary data without having to convert it.  Later, we are going to discuss referencing external entities such as binary data and other XML files.  However, if you want to embed such data within a single entity, CDATA is the place to store it.  Just make sure that the resulting UUENCODED data does not contain a CDATA end tag (]]>).